package com.geekhole.demo.user.application.v2.application;

import com.geekhole.demo.user.application.UserApplication;
import com.geekhole.demo.user.domain.CreateAndEnableUserContext;
import com.geekhole.demo.user.domain.ModifyUserNameContext;
import com.geekhole.demo.user.domain.User;
import com.geekhole.demo.user.domain.UserNotFoundException;
import com.geekhole.demo.user.application.v2.service.base.AbstractCreateService;
import com.geekhole.demo.user.application.v2.service.base.AbstractUpdateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

@Service
public class UserV2Application2
    implements UserApplication {
    @Autowired
    private JpaRepository<User, Long> repository;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void createAndEnableUser(CreateAndEnableUserContext context) {
        // 使用匿名内部类实现逻辑
        new AbstractCreateService<User, CreateAndEnableUserContext>(this.repository, applicationEventPublisher){
            @Override
            protected User instance(CreateAndEnableUserContext context) {
                return User.create(context.getName(), context.getAge());
            }

            @Override
            protected void update(User agg, CreateAndEnableUserContext context) {
                agg.enable();
            }
        }.handle(context);
    }

    @Override
    public void modifyUserName(ModifyUserNameContext context) {
        // 使用匿名内部类实现逻辑
        new AbstractUpdateService<User, ModifyUserNameContext>(this.repository, this.applicationEventPublisher){
            @Override
            protected void update(User agg, ModifyUserNameContext context) {
                agg.modifyUserName(context.getNewName());
            }

            @Override
            protected void notFound(ModifyUserNameContext context) {
                throw new UserNotFoundException(context.getUserId());
            }

            @Override
            protected User loadAgg(ModifyUserNameContext context) {
                return repository.getById(context.getUserId());
            }
        }.handle(context);
    }
}
